<?php
require_once('../includes/settings.php');
require_once('../includes/functions.php');
require_once('../includes/repository.php');
require_once('../includes/sql.php');

deny_get_request();
deny_anonymous();
parameters_check($_REQUEST['action']);

$action = strtolower($_REQUEST['action']);
$user_id = user_val('id');

function is_collected_by_otherone($note_id,$user_id){
	$sql = "SELECT count(id) count FROM voca.voca_user_notes WHERE note_id=? AND user_id != ?";
	$stmt = Repository::prepare($sql);
	$stmt -> bind_param('ii', $note_id,$user_id);
	$stmt -> execute();
	$result = Repository::get_result($stmt);
	return  $result[0]['count']>0;
}

if($action=="save"){
	$word_id=intval($_POST['word_id']);
	$note_id = '';
	if(isset($_POST['note_id'])){
		$note_id = intval($_POST['note_id']);
	}
	$note = trim($_POST['note']);
	if($note==''){
		_jsonp(FALSE,array("error"=>'Invalid Parameters'));
		exit();
	}
	$note = compact_string($note);
	if($note_id==''){
		$note_id = Note::create($word_id,$note,$user_id);
	}else{
		Note::update($note_id,$note);
	}
	Repository::commit();
	Repository::close();
	_jsonp(TRUE,array("note_id"=>$note_id));
	

}elseif ($action=='like') {
	$note_id = intval($_POST['note_id']);
	$id=Note::create_user_note($user_id, $note_id, FALSE);
	Repository::commit();
	Repository::close();
	_jsonp(TRUE);

}elseif ($action=="dislike") {
	$note_id = intval($_POST['note_id']);
	Note::remove_user_note($user_id,$note_id);
	Note::add_to_blacklist($note_id, $user_id);
	Repository::commit();
	Repository::close();
	_jsonp(TRUE);

}elseif($action=="remove"){
	$note_id = intval($_POST['note_id']);
	if( is_collected_by_otherone($note_id, $user_id) ){//移除关联并加入黑名单
		Note::remove_user_note($user_id, $note_id);
		Note::add_to_blacklist($note_id, $user_id);
		Repository::commit();
		Repository::close();
	}else{
		Note::remove($note_id);
		Note::remove_user_note($user_id, $note_id);
		Repository::commit();
		Repository::close();
	}
	_jsonp(TRUE);
}

?>